package cm.tl.pms.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.temporal.IsoFields;
import java.util.Calendar;
import java.util.Date;

/**
 * 季度工具类
 *
 * @author: lwp
 * @date: 2024/10/23 14:08
 * @description
 * @version: 1.0
 */
@Slf4j
public class QuarterUtil {

    /**
     * 获取当前季度
     *
     * @return
     */
    public static String getCurrentQuarter() {
        LocalDate currentDate = LocalDate.now();
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();
        int quarter = (month - 1) / 3 + 1; // 计算季度
        return year + "-" + quarter;
    }

    /**
     * 获取指定时间的季度
     *
     * @param dateTime 指定的时间
     * @return 指定时间的季度
     */
    public static String getQuarter(LocalDateTime dateTime) {
        LocalDate date = dateTime.toLocalDate();
        int year = date.getYear();
        int month = date.getMonthValue();
        int quarter = (month - 1) / 3 + 1; // 计算季度
        return year + "-" + quarter;
    }

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取当前季度的开始时间 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getCurrQuarterStartTime() {
        Calendar calendar = Calendar.getInstance();
        int currentMonth = calendar.get(Calendar.MONTH) + 1;
        int startMonth = (currentMonth - 1) / 3 * 3 + 1;

        return getFormattedDate(calendar, startMonth, 1, 0, 0, 0);
    }

    /**
     * 获取当前季度的结束时间 yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getCurrQuarterEndTime() {
        Calendar calendar = Calendar.getInstance();
        int currentMonth = calendar.get(Calendar.MONTH) + 1;
        int endMonth = ((currentMonth - 1) / 3 + 1) * 3;

        return getFormattedDate(calendar, endMonth, calendar.getActualMaximum(Calendar.DAY_OF_MONTH), 23, 59, 59);
    }

    /**
     * 设置日历对象并返回格式化后的日期字符串
     *
     * @param calendar 日历对象
     * @param month    月份
     * @param day      日期
     * @param hour     小时
     * @param minute   分钟
     * @param second   秒
     * @return 格式化后的日期字符串
     */
    private static String getFormattedDate(Calendar calendar, int month, int day, int hour, int minute, int second) {
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, 0);

        Date date = calendar.getTime();
        return DATE_FORMAT.format(date);
    }

    public static void main(String[] args) {
        // System.out.println("当前季度末月15号: " + getNowQuarter());
        System.out.println("当前季度的中间月份: " + getMiddleMonthOfQuarter());
    }


    //获取当前季度年份
    //格式：2024年第4季度（10月-12月）
    public static String getNowQuarter() {
        // 获取当前时间
        Calendar calendar = Calendar.getInstance();

        // 获取当前年份
        int year = calendar.get(Calendar.YEAR);

        // 获取当前月份（0-11）
        int month = calendar.get(Calendar.MONTH);

        // 计算季度
        int quarter = (month / 3) + 1;

        // 计算月份范围
        int startMonth = (quarter - 1) * 3 + 1; // 季度开始月份（1-12）
        int endMonth = startMonth + 2; // 季度结束月份

        // 输出结果
        System.out.printf("%d年第%d季度（%d月-%d月）%n", year, quarter, startMonth, endMonth);

        return year + "年第" + quarter + "季度（" + startMonth + "月-" + endMonth + "月）";
    }

    public static String parseCheckPeriod(String checkPeriod) {

        if (StringUtils.isBlank(checkPeriod)) {
            return getNowQuarter();
        }
        try {
            String[] split = checkPeriod.split("-");

            // 获取当前年份
            int year = Integer.valueOf(split[0]);

            // 获取当前月份（0-11）
            int quarter = Integer.valueOf(split[1]);

            // 计算月份范围
            int startMonth = (quarter - 1) * 3 + 1; // 季度开始月份（1-12）
            int endMonth = startMonth + 2; // 季度结束月份

            // 输出结果
            System.out.printf("%d年第%d季度（%d月-%d月）%n", year, quarter, startMonth, endMonth);

            return year + "年第" + quarter + "季度（" + startMonth + "月-" + endMonth + "月）";
        } catch (Exception e) {
            e.printStackTrace();
            return getNowQuarter();
        }

    }

    /**
     * 验证是否截止
     *
     * @param checkDeadlineTime
     * @return true ：已经截止 ，false ： 未截止
     */
    public static boolean checkCutoff(String checkDeadlineTime) {
        LocalDate cutOffDate = null;
        LocalDate today = LocalDate.now();
        // today = LocalDate.of(2024, 12, 20);
        today = LocalDate.of(2025, 12, 20);
        cutOffDate = acquisitionDeadline(checkDeadlineTime);
        // 检查当前日期是否大于或等于截止日期
        return today.isAfter(cutOffDate) || today.isEqual(cutOffDate);
    }

    /**
     * 获取截止时间
     *
     * @param checkDeadlineTime
     * @return
     */
    @NotNull
    public static LocalDate acquisitionDeadline(String checkDeadlineTime) {
        LocalDate cutOffDate;
        if ("1".equals(checkDeadlineTime)) {
            cutOffDate = getEndOfQuarter15th();
        } else {
            cutOffDate = getEndOfQuarterLastDay();
        }
        return cutOffDate;
    }

    /**
     * 获取当前季度末月15号
     *
     * @return
     */
    public static LocalDate getEndOfQuarter15th() {
        LocalDate now = LocalDate.now();
        int quarter = now.get(IsoFields.QUARTER_OF_YEAR);
        int year = now.getYear();

        Month endMonthOfQuarter;
        switch (quarter) {
            case 1:
                endMonthOfQuarter = Month.MARCH;
                break;
            case 2:
                endMonthOfQuarter = Month.JUNE;
                break;
            case 3:
                endMonthOfQuarter = Month.SEPTEMBER;
                break;
            case 4:
                endMonthOfQuarter = Month.DECEMBER;
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + quarter);
        }

        return LocalDate.of(year, endMonthOfQuarter, 15);
    }

    /**
     * 获取季度末月最后一天
     *
     * @return
     */
    public static LocalDate getEndOfQuarterLastDay() {
        LocalDate now = LocalDate.now();
        int quarter = now.get(IsoFields.QUARTER_OF_YEAR);
        int year = now.getYear();

        Month endMonthOfQuarter;
        switch (quarter) {
            case 1:
                endMonthOfQuarter = Month.MARCH;
                break;
            case 2:
                endMonthOfQuarter = Month.JUNE;
                break;
            case 3:
                endMonthOfQuarter = Month.SEPTEMBER;
                break;
            case 4:
                endMonthOfQuarter = Month.DECEMBER;
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + quarter);
        }

        return LocalDate.of(year, endMonthOfQuarter, endMonthOfQuarter.length(now.isLeapYear()));
    }

    public static String getLastMonthDateStr() {
        // 获取当前日期
        DateTime currentDate = DateUtil.date();

        // 获取上个月的日期
        DateTime previousMonthDate = DateUtil.offsetMonth(currentDate, -1);

        // 获取上个月的年月
        int previousYear = previousMonthDate.year();
        int previousMonth = previousMonthDate.month() + 1; // 月份从 0 开始，需要加 1

        // 格式化为 yyyy年MM月
        String formattedDate = String.format("%d年%02d月", previousYear, previousMonth);

        // 输出结果
        return formattedDate;
    }

    /**
     * 获取当前季度的中间月份，并格式化为 yyyy年-m月
     *
     * @return 当前季度的中间月份，格式为 yyyy年-m月
     */
    public static String getMiddleMonthOfQuarter() {
        LocalDate now = LocalDate.now();
        int currentMonth = now.getMonthValue();
        int quarter = (currentMonth - 1) / 3 + 1;
        int middleMonth = (quarter - 1) * 3 + 2; // 季度的中间月份

        LocalDate middleMonthDate = LocalDate.of(now.getYear(), middleMonth, 1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年-M月");

        return middleMonthDate.format(formatter);
    }
}
